package tr.edu.metu.is550.isell.utils;

import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class RestClient {

    static class Builder {
        private RestClient client;

        Builder(String url, RequestMethod mtd) {
            client = new RestClient(url);
            client.setMethod(mtd);
        }

        public Builder entity(JSONObject entity) {
            client.setEntity(entity);
            return this;
        }

        public RestClient build() {
            return client;
        }
    }

    RestClient(String url) {
        this.url = url;
    }

    private String url;
    private RequestMethod method;
    private JSONObject entity;

    public void setMethod(RequestMethod method) {
        this.method = method;
    }

    private void setEntity(JSONObject entity) {
        this.entity = entity;
    }

    public static Builder post(String url) {
        return new Builder(url, RequestMethod.POST);
    }

    public void execute() {
        DefaultHttpClient client = new DefaultHttpClient();

        HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
                AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                if (authState.getAuthScheme() == null) {
                    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    Credentials creds = credsProvider.getCredentials(authScope);
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }
        };

        client.addRequestInterceptor(preemptiveAuth, 0);

        try {
            //HttpResponse response = client.execute(createRequest());
            //String result = convertStreamToString(response.getEntity().getContent());
            //return new JSONObject(result);

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

    }


    private String convertStreamToString(InputStream is) {
        /*
        * To convert the InputStream to String we use the BufferedReader.readLine()
        * method. We iterate until the BufferedReader return null which means
        * there's no more data to read. Each line will appended to a StringBuilder
        * and returned as String.
        */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }


}


/*
public class Builder {
    private RequestMethod method;
    private String url;
    private JSONObject jsonObject;

    public Builder(String Url, RequestMethod method) {
        this.url = url;
        this.method = method;
    }

    public Builder entity(JSONObject obj) {
        this.jsonObject = obj;
        return this;
    }

    public JSONObject execute() {
    }

    private HttpUriRequest createRequest(){
        HttpUriRequest request = null;

        if(RequestMethod.POST.equals(method)){
            HttpPost r = new HttpPost(this.url);
            r.setEntity(new ByteArrayEntity(jsonObject.toString().getBytes()));
        }

        request.setHeader("Content-Type","application/json");
        request.setHeader("Accept","application/json");

        return request;

    }

*/






